package com.nus.fellowmark.common.utils;

import java.io.*;

/**
 * @author Ruoyi Chen
 * @email chenruoyisz@gmail.com
 * @create 2023/2/17
 */
public class FileUtils {
    public static final int DEFAULT_BUFFER_SIZE = 8192;

    public static void writeBytes(String filePath, OutputStream os) throws IOException {
        FileInputStream fis = null;
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                throw new FileNotFoundException(filePath);
            }
            fis = new FileInputStream(file);
            byte[] b = new byte[1024];
            int length;
            while ((length = fis.read(b)) > 0) {
                os.write(b, 0, length);
            }
        } catch (IOException e) {
            throw e;
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    public static Boolean outputFile(BufferedOutputStream out, InputStream in) {

        byte[] buffer = new byte[1024];
        int length = 0;
        try {
            while ((length = in.read(buffer)) != -1) {
                out.write(buffer, 0, length);
            }
            try {
                if (out != null) {
                    out.flush();
                }
            } catch (IOException e) {
                e.printStackTrace();
                return Boolean.FALSE;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return Boolean.FALSE;
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return Boolean.TRUE;

    }
}
